"use client"

import React from "react"
import { Box, TextField, IconButton, Tooltip, Paper } from "@mui/material"
import { Send as SendIcon, AttachFile as AttachIcon } from "@mui/icons-material"
import useAppStore from "@/store/useAppStore"
import DocumentUpload from "./DocumentUpload"
import { parseWordDocument, extractMainContent, ParsedDocument } from "@/app/services/wordParser"

export default function ChatInput() {
	const [inputValue, setInputValue] = React.useState("")
	const [showUpload, setShowUpload] = React.useState(false)
	const [parsedDocument, setParsedDocument] = React.useState<ParsedDocument | null>(null)
	const {
		addMessage,
		messages,
		selectedApi,
		selectedDeepSeekModel,
		setIsLoading,
		setError,
		isLoading,
		updateMessage,
		selectedFile,
		setSelectedFile,
		isUploading,
		setIsUploading,
		uploadError,
		setUploadError
	} = useAppStore()

	// 处理文件选择 - 自动解析Word文档
	const handleFileSelect = async (file: File) => {
		try {
			console.log("开始处理文件:", file.name, file.type, file.size)
			setIsUploading(true)
			setUploadError(null)

			// 解析Word文档
			console.log("开始解析Word文档...")
			const parsed = await parseWordDocument(file)
			console.log("Word文档解析完成:", parsed)

			setParsedDocument(parsed)

			// 同时设置原始文件（用于向后兼容）
			setSelectedFile(file)

			console.log("Word文档解析成功:", {
				title: parsed.metadata?.title,
				textLength: parsed.text.length,
				htmlLength: parsed.html.length,
				textPreview: parsed.text.substring(0, 100) + "..."
			})
		} catch (error) {
			console.error("Word文档解析失败:", error)
			setUploadError(error instanceof Error ? error.message : "文档解析失败")
		} finally {
			setIsUploading(false)
		}
	}

	// 读取文件为Base64（保留用于向后兼容）
	const readFileAsBase64 = (file: File): Promise<string> => {
		return new Promise((resolve, reject) => {
			const reader = new FileReader()
			reader.onload = () => {
				const result = reader.result as string
				// 移除data:application/vnd.openxmlformats-officedocument.wordprocessingml.document;base64,前缀
				const base64 = result.split(",")[1]
				resolve(base64)
			}
			reader.onerror = reject
			reader.readAsDataURL(file)
		})
	}

	const handleSendMessage = async () => {
		if (inputValue.trim() || selectedFile || parsedDocument) {
			let userMessage = inputValue.trim()

			// 如果有解析后的文档，只显示附件标签
			if (parsedDocument) {
				const documentTitle = parsedDocument.metadata?.title || selectedFile?.name || "文档"
				const documentContent = extractMainContent(parsedDocument)

				if (userMessage) {
					userMessage = `${userMessage}\n\n📎 **附件: ${documentTitle}**`
				} else {
					userMessage = `请帮我处理这个Word文档的内容，将其转换为HTML格式。\n\n📎 **附件: ${documentTitle}**`
				}
			} else if (selectedFile) {
				// 向后兼容：如果没有解析后的文档但有原始文件
				userMessage = userMessage
					? `${userMessage}\n\n📎 **附件: ${selectedFile.name}**`
					: `请帮我转换这个Word文档为HTML格式。\n\n📎 **附件: ${selectedFile.name}**`
			}

			addMessage("user", userMessage)
			// 立即添加AI加载消息，让用户看到AI气泡
			const assistantMessageId = addMessage("assistant", "正在思考中...")
			setInputValue("")
			setIsLoading(true)
			setError(null)
			setUploadError(null)

			try {
				// 准备请求数据
				const requestData: any = {
					messages: [...messages, { role: "user", content: userMessage, id: "" }],
					selectedApi,
					selectedDeepSeekModel
				}

				// 如果有解析后的文档，添加解析后的数据（包含完整内容供AI处理）
				if (parsedDocument) {
					const documentContent = extractMainContent(parsedDocument)
					requestData.document = {
						name: parsedDocument.metadata?.title || selectedFile?.name || "文档",
						type: "parsed",
						content: {
							html: parsedDocument.html,
							text: parsedDocument.text,
							mainContent: documentContent, // 主要文本内容
							metadata: parsedDocument.metadata
						}
					}
					console.log("发送解析后的文档给AI:", {
						name: requestData.document.name,
						type: requestData.document.type,
						mainContentLength: documentContent.length,
						htmlLength: parsedDocument.html.length,
						textLength: parsedDocument.text.length
					})
				} else if (selectedFile) {
					// 向后兼容：如果没有解析后的文档但有原始文件
					setIsUploading(true)
					const fileContent = await readFileAsBase64(selectedFile)
					requestData.document = {
						name: selectedFile.name,
						type: selectedFile.type,
						size: selectedFile.size,
						content: fileContent
					}
				}

				const response = await fetch("/api/ai/chat", {
					method: "POST",
					headers: {
						"Content-Type": "application/json"
					},
					body: JSON.stringify(requestData)
				})

				if (!response.ok || !response.body) {
					throw new Error(`HTTP error! status: ${response.status}`)
				}

				// 处理流式响应
				const reader = response.body.getReader()
				const decoder = new TextDecoder()
				let buffer = "" // 用于处理跨chunk的thinking标签
				let isFirstContent = true // 标记是否是第一次收到内容
				// 60fps流式输出优化
				let pendingContent = "" // 待更新的内容
				let lastRenderTime = 0 // 上次渲染时间
				let animationFrameId: number | null = null // 动画帧ID
				const TARGET_FPS = 60 // 目标帧率
				const FRAME_INTERVAL = 1000 / TARGET_FPS // 16.67ms

				// 60fps渲染函数
				const renderContent = (currentTime: number) => {
					// 检查是否到了渲染时间
					if (currentTime - lastRenderTime >= FRAME_INTERVAL && pendingContent) {
						updateMessage(assistantMessageId, pendingContent)
						pendingContent = ""
						lastRenderTime = currentTime
					}

					// 如果还有待渲染内容，继续安排下一帧
					if (pendingContent) {
						animationFrameId = requestAnimationFrame(renderContent)
					} else {
						animationFrameId = null
					}
				}

				// 智能更新函数 - 累积内容后按60fps渲染
				const smartUpdate = (content: string, isReplace = false) => {
					if (isReplace) {
						// 替换操作立即执行
						updateMessage(assistantMessageId, content, undefined, true)
						pendingContent = ""
						// 取消动画帧
						if (animationFrameId) {
							cancelAnimationFrame(animationFrameId)
							animationFrameId = null
						}
						return
					}

					// 累积内容
					pendingContent += content

					// 如果还没有安排渲染，则安排
					if (!animationFrameId) {
						animationFrameId = requestAnimationFrame(renderContent)
					}
				}

				// 处理待更新内容
				const flushPendingContent = () => {
					if (pendingContent) {
						updateMessage(assistantMessageId, pendingContent)
						pendingContent = ""
					}
					// 取消未完成的动画帧
					if (animationFrameId) {
						cancelAnimationFrame(animationFrameId)
						animationFrameId = null
					}
				}

				while (true) {
					const { done, value } = await reader.read()
					if (done) break

					const chunk = decoder.decode(value, { stream: true })
					buffer += chunk

					// 调试日志
					console.log("收到chunk:", chunk)

					// 处理完整的thinking标签
					let thinkingMatch
					while ((thinkingMatch = buffer.match(/<thinking>([\s\S]*?)<\/thinking>/))) {
						const thinkingContent = thinkingMatch[1]
						console.log("解析到完整thinking内容:", thinkingContent)
						updateMessage(assistantMessageId, "", thinkingContent)

						// 从buffer中移除已处理的thinking内容
						buffer = buffer.replace(thinkingMatch[0], "")
					}

					// 处理剩余的普通内容（不在thinking标签内的）
					const remainingContent = buffer.replace(/<thinking>[\s\S]*$/, "") // 移除未完成的thinking开始标签
					if (remainingContent.trim()) {
						console.log("处理正常内容:", remainingContent)
						if (isFirstContent) {
							// 第一次收到内容时，替换掉"正在思考中..."文本
							smartUpdate(remainingContent, true)
							isFirstContent = false
						} else {
							// 后续内容使用60fps智能更新
							smartUpdate(remainingContent)
						}
						buffer = buffer.replace(remainingContent, "")
					}
				}

				// 处理最后可能剩余的内容
				if (buffer.trim()) {
					console.log("处理最后剩余内容:", buffer)
					if (isFirstContent) {
						// 如果这是第一次也是最后一次内容，替换加载文本
						smartUpdate(buffer, true)
					} else {
						// 否则使用60fps智能更新
						smartUpdate(buffer)
					}
				}

				// 确保所有待更新内容都被处理
				flushPendingContent()
			} catch (e) {
				const error = e as Error
				setError(error.message)
				addMessage("assistant", `抱歉，处理时遇到错误：${error.message}`)
				console.error("Failed to get AI response:", error)
			} finally {
				setIsLoading(false)
				setIsUploading(false)
				// 发送成功后清除文档
				if (selectedFile) {
					setSelectedFile(null)
				}
				if (parsedDocument) {
					setParsedDocument(null)
				}
			}
		}
	}

	const handleKeyPress = (event: React.KeyboardEvent) => {
		if (event.key === "Enter" && !event.shiftKey) {
			event.preventDefault()
			handleSendMessage()
		}
	}

	return (
		<Box
			sx={{
				p: { xs: 1, sm: 1.5 }, // 减少内边距
				bgcolor: "background.paper",
				borderTop: "1px solid",
				borderColor: "divider"
			}}
		>
			{/* 文档上传组件 */}
			{showUpload && (
				<DocumentUpload
					onFileSelect={handleFileSelect}
					onRemove={() => {
						setSelectedFile(null)
						setParsedDocument(null)
					}}
					onClose={() => setShowUpload(false)}
					selectedFile={selectedFile}
					isUploading={isUploading}
					error={uploadError}
				/>
			)}

			<Paper
				elevation={0}
				sx={{
					display: "flex",
					alignItems: "flex-end",
					gap: { xs: 1, sm: 1.5 },
					p: { xs: 1.5, sm: 2 },
					borderRadius: { xs: 2.5, sm: 3 }, // 与消息气泡保持一致的圆角
					border: "1px solid",
					borderColor: "grey.300",
					bgcolor: "background.paper",
					transition: "all 0.2s ease-in-out",
					"&:focus-within": {
						borderColor: "primary.main",
						boxShadow: "0 2px 8px rgba(37, 99, 235, 0.15)", // 更柔和的阴影
						transform: "translateY(-1px)" // 微妙的提升效果
					},
					"&:hover": {
						borderColor: "grey.400",
						boxShadow: "0 1px 4px rgba(0,0,0,0.08)"
					}
				}}
			>
				<TextField
					fullWidth
					multiline
					maxRows={4}
					variant='standard'
					placeholder='输入你的内容或指令 (Shift + Enter 换行)'
					value={inputValue}
					onChange={e => setInputValue(e.target.value)}
					onKeyPress={handleKeyPress}
					disabled={isLoading}
					InputProps={{
						disableUnderline: true,
						sx: {
							fontSize: { xs: "0.95rem", sm: "1rem" },
							lineHeight: 1.6,
							padding: 0,
							color: "text.primary",
							"&::placeholder": {
								color: "text.secondary",
								opacity: 0.8
							}
						}
					}}
					sx={{
						"& .MuiInputBase-root": {
							padding: 0,
							minHeight: "auto"
						},
						"& .MuiInputBase-input": {
							padding: 0,
							"&::placeholder": {
								opacity: 0.7,
								fontStyle: "italic"
							}
						}
					}}
				/>

				{/* 附件按钮 */}
				<Tooltip title={showUpload ? "隐藏文档上传" : "上传文档"}>
					<IconButton
						onClick={() => setShowUpload(!showUpload)}
						disabled={isLoading}
						sx={{
							color: showUpload ? "primary.main" : "grey.600",
							width: { xs: 36, sm: 40 },
							height: { xs: 36, sm: 40 },
							borderRadius: 2,
							transition: "all 0.2s ease-in-out",
							"&:hover": {
								bgcolor: showUpload ? "primary.50" : "grey.100",
								transform: "scale(1.05)"
							}
						}}
					>
						<AttachIcon fontSize='small' />
					</IconButton>
				</Tooltip>

				<Tooltip title='发送'>
					<span>
						<IconButton
							onClick={handleSendMessage}
							disabled={isLoading || (!inputValue.trim() && !selectedFile && !parsedDocument)}
							sx={{
								bgcolor: "primary.main",
								color: "white",
								width: { xs: 36, sm: 40 },
								height: { xs: 36, sm: 40 },
								borderRadius: 2,
								boxShadow: "0 2px 8px rgba(37, 99, 235, 0.3)",
								transition: "all 0.2s ease-in-out",
								"&:hover": {
									bgcolor: "primary.dark",
									transform: "scale(1.05)",
									boxShadow: "0 4px 12px rgba(37, 99, 235, 0.4)"
								},
								"&:disabled": {
									bgcolor: "grey.300",
									color: "grey.500",
									boxShadow: "none",
									transform: "none"
								}
							}}
						>
							<SendIcon fontSize='small' />
						</IconButton>
					</span>
				</Tooltip>
			</Paper>
		</Box>
	)
}
